package ym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ym.mapper.AppointmentMapper;
import ym.mapper.HouseMapper;
import ym.mapper.UserMapper;
import ym.pojo.Appointment;
import ym.pojo.House;
import ym.pojo.User;
import ym.service.AppointmentService;
import ym.service.UserService;

import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class AppointmentServiceImpl implements AppointmentService {
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private HouseMapper houseMapper;

    @Override
    public void addNumber(Appointment appointment) {
        //把时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        String format = sdf.format(appointment.getAppointmentTime());
        appointment.setAppointmentTime(format);
        appointmentMapper.insert(appointment);
    }
    @Override
    public void addString(Appointment appointment) {
        appointmentMapper.insert(appointment);
    }

    @Override
    public void delete(Integer id) {
        appointmentMapper.deleteById(id);
    }

    @Override
    public Appointment findById(Integer id) {
        Appointment appointment = appointmentMapper.selectById(id);
        //封装房源
        House house = houseMapper.selectById(appointment.getHouseId());
        appointment.setHouse(house);
        //封装用户
        User user = userService.findById(appointment.getUserId());
        appointment.setUser(user);
        return appointment;

    }

    @Override
    public List<Appointment> findAllByUserId(Integer userId) {
        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        List<Appointment> appointmentList = appointmentMapper.selectList(queryWrapper);
        for (Appointment appointment : appointmentList) {
            //封装房源
            House house = houseMapper.selectById(appointment.getHouseId());
            appointment.setHouse(house);
            //封装用户
            User user = userService.findById(appointment.getUserId());
            appointment.setUser(user);
        }
        return appointmentList;
    }
}
